
<!--
 * @Author: 黄达全
 * @Date: 2024-07-29 14:38:50
 * @LastEditTime: 2024-08-21 13:46:40
-->
<script lang="ts" setup>
import { reactive, ref, onMounted, nextTick } from "vue"
import type { FormRules } from "element-plus"
import type { ManagerVO, ManagerAddForm, RoleXiaLaOptions ,ManagerXiaLaOptions,ManagerFilterForm} from "@/common/type"
import ManagerApi from "@/api/model/manager"
import drawer from "@/components/drawer.vue"
import useElementPlus from "@/hooks/useElementPlus"
import avatar from "@/components/avatar.vue"
import selectImage from "@/components/selectImage.vue"
import type { ImagePageItem } from "@/common/type"
import RoleApi from "@/api/model/role"

const height = document.documentElement.clientHeight - 44.33 - 42 - 60.67 - 14;

const isManagerAdd = ref(true)
const managerDrawerRef = ref()
const selectImageRef = ref()
// 打开公告新增抽屉
const openAddManagerDrawer = () => {
    isManagerAdd.value = true
    managerForm.username = ""
    managerForm.password = ""
    managerForm.avatar = ""
    managerForm.roleId = null
    managerForm.status = false
    managerDrawerRef.value.open()
    getRoleData()

    nextTick(() => {
        selectImageRef.value.init_checked()
    })
}
// 打开公告编辑抽屉
const managerEditId = ref<number>()
const openEditManagerDrawer = (manager: ManagerVO) => {
    isManagerAdd.value = false
    managerForm.username = manager.username
    managerForm.password = ""
    managerForm.avatar = manager.avatar
    managerForm.roleId = manager.roleId!
    managerForm.status = manager.status ? true : false

    managerEditId.value = manager.id
    managerDrawerRef.value.open()
    getRoleData()
    nextTick(() => {
        selectImageRef.value.init_checked()
    })
}

// 公告表单
const managerForm = reactive<ManagerAddForm>({
    username: "",
    password: null,
    avatar: "",
    roleId: null,
    status: false
})
// 表单校验规则
const managerFormRules = reactive<FormRules<typeof managerForm>>({
    username: [
        { required: true, message: "请输入用户名", trigger: "blur" },
    ],
    password: [
        { min: 6, message: "密码长度不能小于6位", trigger: "blur" },
        { max: 18, message: "密码长度不能大于18位", trigger: "blur" },
        { pattern: /^[a-zA-Z0-9]{6,18}$/, message: "密码只能包含字母和数字", trigger: "blur" },
    ],
    roleId: [
        { required: true, message: "请选择角色", trigger: "blur" },
    ]
})
const { message, messageBox } = useElementPlus()

const page = ref(1)
const pageSize = ref(10)
const total = ref(0)
const managerData = ref<ManagerVO[]>([])

const getManagerData = async (form?:ManagerFilterForm) => {
    const { data } = await ManagerApi.page(page.value, pageSize.value,form)
    total.value = data.total
    managerData.value = data.records
}
getManagerData()

const roleDataOptions = ref<RoleXiaLaOptions[]>([])
const getRoleData = async () => {
    const { data } = await RoleApi.selectXiaLa()
    roleDataOptions.value = data.map(item => {
        return {
            label: item.name,
            value: item.id
        }
    })
}
getRoleData()

const addManager = async () => {
    const form: any = managerForm
    form.status = form.status ? 1 : 0
    const { code } = await ManagerApi.add(form)
    if (code == 1) {
        message({
            message: "新增管理员成功",
            type: "success"
        })
        getManagerData()
        managerDrawerRef.value.close()
    }

}
const editManager = async () => {
    const form: any = managerForm
    form.status = form.status ? 1 : 0
    if(form.password==='' || form.password.length===0){
        form.password = null
    }
    const { code } = await ManagerApi.update(managerEditId.value!, form)
    if (code == 1) {
        message({
            message: "编辑管理员成功",
            type: "success"
        })
        getManagerData()
        managerDrawerRef.value.close()
    }
}

const deleteIds = ref<number[]>([])
const handleSelectionChange = (rows: ManagerVO[]) => {
    deleteIds.value = rows.map((item) => item.id)
}

const deleteManager = async (id: number) => {
    messageBox('提示', '你正在删除此管理员，是否继续?').then(async () => {
        const ids = typeof id === "number" ? [id] : Array.from(deleteIds.value)
        const { code } = await ManagerApi.delete(ids)
        if (code == 1) {
            message({
                message: "删除管理员成功",
                type: "success"
            })
            getManagerData()
        }
    }).catch((err) => {
        console.log(err)
        message({
            message: "取消删除管理员",
            type: "info"
        })
    })
}
// 封禁
const banned = async (status: number) => {
    messageBox('提示', `你正在${status ? '解封' : '封禁'}此管理员，是否继续?`).then(async () => {
        const ids = Array.from(deleteIds.value)
        const { code } = await ManagerApi.banned(ids, status)
        if (code == 1) {
            message({
                message: `${status ? '解封' : '封禁'}管理员成功`,
                type: "success"
            })
            getManagerData()
        }
    }).catch((err) => {
        console.log(err)
        message({
            message: `取消${status ? '解封' : '封禁'}管理员`,
            type: "info"
        })
    })
}

const getManagerDataByPage = (e: number) => {
    page.value = e
    getManagerData(filterForm)
}

// 公告内容的提交
const managerSubmitHandle = () => {
    isManagerAdd.value ? addManager() : editManager()
}

// 表格高度
const managerTableRef = ref<HTMLDivElement>()
const managerHeight = ref<number>(0)
onMounted(() => {
    managerHeight.value = managerTableRef.value!.clientHeight
})

// 获取头像
type ImagePageItem_Check = ImagePageItem & { checked: boolean }
const selectImageHandle = (imageList: ImagePageItem_Check[]) => {
    const image = imageList[0]
    managerForm.avatar = image.url
}

// 表格多选框是否勾选
const selectable = (row: ManagerVO, _index: number) => {
    return row.isSuper != 1
}

// 过滤表单节点
const filterFormRef=ref()
// 过滤表单
const filterForm = reactive<ManagerFilterForm>({
    username: null,
    status: null,
    roleId: null,
    createManagerId:null,
    lastUpdateManagerId:null
})
// 获取下拉菜单
const managerSelectOptions=ref<ManagerXiaLaOptions[]>([])
const getManagerSelectData=async()=>{
    const {data}=await ManagerApi.selectXiaLa()
    managerSelectOptions.value=data.map(item=>{
        return {
            label:item.username,
            value:item.id
        }
    })
}
getManagerSelectData()


// 搜索
const filterSearch=()=>{
    page.value=1
    getManagerData(filterForm)
}

// 分页当前页
const currentPage=ref(1)
// 重置表单
const resetFilterForm=()=>{
    filterForm.username=null
    filterForm.status=null
    filterForm.roleId=null
    filterForm.createManagerId=null
    filterForm.lastUpdateManagerId=null
    currentPage.value=1
    page.value=1
    filterFormRef.value.resetFields()
    getManagerData()
}

// 搜索输入框
const filterForm_usernameInputChange=()=>{
    if(filterForm.username?.length==0){
        filterForm.username=null
        getManagerData(filterForm)
    }
}
</script>

<template>
    <div class="ManagerPage">
        <el-card class="card" :body-style="{ height: height + 'px', padding: '10px 10px 0 10px' }">
            <template #header>
                <div class="card-header">
                    <div class="card-header-left">
                        <el-button color="var(--primary-theme-color)" icon="el-icon-plus" size="small" type="primary"
                        @click="openAddManagerDrawer">新增管理员</el-button>
                    <el-button size="small" type="danger" @click="deleteManager" icon="el-icon-delete">批量删除</el-button>
                    <el-button size="small" type="danger" @click="banned(0)" icon="el-icon-lock">批量封禁</el-button>
                    <el-button size="small" type="success" @click="banned(1)" icon="el-icon-key">批量解封</el-button>
                    </div>
                    <div class="card-header-right">
                        <el-button  icon="el-icon-refresh-left" size="small" type="primary" @click="resetFilterForm">重置表单</el-button>
                        <el-button color="var(--primary-theme-color)" icon="el-icon-search" size="small" type="success" @click="filterSearch">搜索</el-button>
                    </div>
                    
                </div>
            </template>
            <div class="card-body">
                <div class="manager-table-filter">
                    <el-form :model="filterForm" ref="filterFormRef" inline>
                        <el-form-item label="管理员名称：">
                            <el-input v-model="filterForm.username" type="text" size="small" placeholder="请输入管理员名称"  @change="filterForm_usernameInputChange"/>
                        </el-form-item>
                        <el-form-item label="封禁状态：">
                            <el-select v-model="filterForm.status" placeholder="请选择状态" size="small" style="width: 100px;">
                                <el-option label="启动" :value="1" />
                                <el-option label="封禁" :value="0" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="角色：">
                        <el-select-v2 style="width: 200px;" size="small" v-model="filterForm.roleId" :options="roleDataOptions" placeholder="请选择角色" />
                    </el-form-item>
                        <el-form-item label="创建人：">
                        <el-select-v2 style="width: 200px;" size="small" v-model="filterForm.createManagerId" :options="managerSelectOptions" placeholder="请选择管理员" />
                    </el-form-item>
                        <el-form-item label="修改人：">
                        <el-select-v2 style="width: 200px;" size="small" v-model="filterForm.lastUpdateManagerId" :options="managerSelectOptions" placeholder="请选择管理员" />
                    </el-form-item>
                    </el-form>
                </div>
                <div class="manager-table" ref="managerTableRef">

                    <el-table :data="managerData" style="width: 99.4%;" stripe @selection-change="handleSelectionChange"
                        :height="managerHeight">
                        <el-table-column type="selection" width="80" align="center" :selectable="selectable" />
                        <el-table-column fixed="left" label="管理员信息" align="center" width="150">
                            <template #default="{ row }">
                                <div class="avatar">
                                    <div class="avatar-area">
                                        <avatar :src="row.avatar" />
                                    </div>
                                    <div class="manager-info">
                                        <div class="username">
                                            {{ row.username }}
                                        </div>
                                        <div class="user_id">管理员ID：{{ row.id }}</div>
                                    </div>
                                </div>
                            </template>

                        </el-table-column>
                        <el-table-column prop="rolename" label="角色" width="100" align="center" />
                        <el-table-column show-overflow-tooltip prop="desc" label="描述" width="200" align="center" />
                        <el-table-column label="状态" width="100" align="center">
                            <template #default="{ row }">
                                <el-tag v-if="row.status == 1" type="success">启动</el-tag>
                                <el-tag v-else type="danger">封禁</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="createManagerName" label="创建人"  align="center" />
                        <el-table-column prop="lastUpdateManagerName" label="修改人"  align="center" />
                        <el-table-column prop="createTime" label="创建时间" width="200" align="center" />
                        <el-table-column prop="updateTime" label="修改时间" width="200" align="center" />
                        <el-table-column fixed="right" label="操作" align="center" width="200">

                            <template #default="{ row }">
                                <el-button type="warning" size="small" v-if="!row.isSuper"
                                    @click="openEditManagerDrawer(row)" icon="el-icon-edit">编辑</el-button>
                                <el-button type="danger" size="small" @click="deleteManager(row.id)"
                                    v-if="!row.isSuper" icon="el-icon-delete">删除</el-button>
                                <el-button link type="info" v-if="row.isSuper">暂无可执行操作</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <div class="pagination">
                    <el-pagination size="small" background layout="prev, pager, next" :total="total"
                        :page-size="pageSize" @current-change="getManagerDataByPage" v-model:current-page="currentPage"/>
                </div>
            </div>
        </el-card>
        <drawer ref="managerDrawerRef" :title="isManagerAdd ? '新增管理员' : '修改管理员'" direction="rtl" size="35%"
            @submit="managerSubmitHandle">
            <template #rtl>
                <el-form :model="managerForm" :rules="managerFormRules" :label-width="100">
                    <el-form-item label="用户名" prop="username">
                        <el-input v-model="managerForm.username"></el-input>
                    </el-form-item>
                    <el-form-item label="密码" prop="password">
                        <el-input type="password" show-password v-model="managerForm.password"></el-input>
                    </el-form-item>
                    <el-form-item label="头像">
                        <selectImage @select-image="selectImageHandle" :multiple="false" :avatarUrl="managerForm.avatar"
                            ref="selectImageRef" />
                    </el-form-item>

                    <el-form-item prop="roleId" label="所属角色">
                        <el-select-v2 v-model="managerForm.roleId" :options="roleDataOptions" placeholder="请选择所属角色" />
                    </el-form-item>
                    <el-form-item label="状态">
                        <el-switch v-model="managerForm.status" />
                    </el-form-item>
                </el-form>
            </template>
        </drawer>
    </div>
</template>

<style lang="scss" scoped>
.ManagerPage {
    height: 100%;
    width: 100%;
    transition: var(--el-transition-duration);
    .card{
        .card-header{
            display: flex;
            justify-content: space-between;
        }
    .card-body {
        height: 100%;
        display: flex;
        flex-direction: column;

        .manager-table-filter {
            height: 40px;
        }

        .manager-table {
            flex: 1;
            overflow-y: scroll;

            .avatar {
                height: 30px;
                display: flex;

                .avatar-area {
                    width: 30px;
                    height: 30px;
                }

                .manager-info {
                    height: 30px;
                    display: flex;
                    flex-direction: column;
                    padding-bottom: 5px;

                    .username {
                        font-size: 12px;
                        height: 15px;
                        color: var(--el-table-text-color);
                        padding: 0 !important;
                        display: flex;
                        justify-content: flex-start;
                        transform: scale(0.8) translateX(-5px) translateY(-4px);
                    }

                    .user_id {
                        font-size: 12px;
                        height: 15px;
                        color: var(--el-table-text-color);
                        padding: 0;
                        display: flex;
                        justify-content: flex-start;
                        transform: scale(0.8) translateX(-5px) translateY(-4px);
                    }
                }
            }


            &::-webkit-scrollbar {
                width: 0;
            }
        }
    }


        .pagination {
            height: 50px;
            display: flex;
            justify-content: center;
            align-items: center;
        }
    }

}

:deep(.el-pagination.is-background .el-pager li.is-active) {
    background-color: var(--primary-theme-color) !important;
    color: #FFFFFF;
}
</style>
